package com.group01.community.config;

import com.alibaba.fastjson2.JSON;
import com.group01.community.entity.SysOperLog;
import com.group01.community.utils.*;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;

/**
 * 操作日志记录处理
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 处理完请求后执行
     *
     * @param joinPoint  切入点
     * @param jsonResult json结果
     */
    @AfterReturning(
            pointcut = "execution(* com.group01.community.controller.*.*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.select*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.get*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.list*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.query*(..)) " +
                    "&& !execution(* com.group01.community.controller.LoginController.info(..))",
            returning = "jsonResult"
    )
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切入点
     * @param e         异常
     */
    @AfterThrowing(
            pointcut = "execution(* com.group01.community.controller.*.*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.select*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.get*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.list*(..)) " +
                    "&& !execution(* com.group01.community.controller.*.query*(..)) " +
                    "&& !execution(* com.group01.community.controller.LoginController.info(..))",
            throwing = "e"
    )
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            SysOperLog operLog = new SysOperLog();
            //类名
            String className = joinPoint.getTarget().getClass().getSimpleName();
            //方法名
            String methodName = joinPoint.getSignature().getName();

            //模块标题
            String s = I18nUtils.handleCN(className);
            operLog.setTitle(s);

            //业务类型
            Integer businessType = null;
            if (methodName.contains(BusinessType.ADD.getUsMSg())) {
                businessType = BusinessType.ADD.getValue();
            } else if (methodName.contains(BusinessType.UPDATE.getUsMSg())) {
                businessType = BusinessType.UPDATE.getValue();
            } else if (methodName.contains(BusinessType.DELETE.getUsMSg())) {
                businessType = BusinessType.DELETE.getValue();
            } else if (methodName.contains(BusinessType.EXPORT.getUsMSg())) {
                businessType = BusinessType.EXPORT.getValue();
            } else if (methodName.contains(BusinessType.IMPORT.getUsMSg())) {
                businessType = BusinessType.IMPORT.getValue();
            } else if (methodName.contains(BusinessType.CLEAR.getUsMSg())) {
                businessType = BusinessType.CLEAR.getValue();
            }
            operLog.setBusinessType(businessType);

            //方法名称
            methodName = joinPoint.getSignature().getDeclaringTypeName().concat("." + methodName + "()");
            operLog.setMethod(methodName);

            //请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());

            //操作类别
            operLog.setOperatorType(1);

            //操作人员
            User loginUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (loginUser != null) {
                operLog.setOperName(loginUser.getUsername());
            }

            //请求的地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());

            //请求参数
            setRequestValue(joinPoint, operLog);

            //返回参数
            operLog.setJsonResult(JSON.toJSONString(jsonResult));

            //操作状态
            operLog.setStatus(0);

            //错误消息
            if (e != null) {
                operLog.setStatus(1);
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }

            // 保存数据库
            AsyncFactory.recordOper(operLog);
        } catch (Exception ex) {
            log.error("==前置通知异常==");
            log.error("异常信息:{}", ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
